<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  
  <title>Android 集成微信登录 | 梁健的博客</title>
  
  
  <meta name="description" content="这是我的博客">
  

  

  <meta name="HandheldFriendly" content="True" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <!-- meta -->
  

  <!-- link -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css">
  
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.10.1/css/all.min.css">
  

  

  
    
<link rel="stylesheet" href="/style.css">

  

  <script>
    function setLoadingBarProgress(num) {
      document.getElementById('loading-bar').style.width=num+"%";
    }
  </script>

  
  
<meta name="generator" content="Hexo 4.2.0"></head>

<body>
  
  
  <div class="cover-wrapper">
    <cover class='cover post half'>
      
        
  <h1 class='title'>梁健的博客</h1>


  <div class="m_search">
    <form name="searchform" class="form u-search-form">
      <input type="text" class="input u-search-input" placeholder="" />
      <i class="icon fas fa-search fa-fw"></i>
    </form>
  </div>

<div class='menu navgation'>
  <ul class='h-list'>
    
      
        <li>
          <a class="nav home" href="/"
            
            
            id="home">
            <i class='fas fa-rss fa-fw'></i>&nbsp;博文
          </a>
        </li>
      
        <li>
          <a class="nav home" href="/friends/"
            
              rel="nofollow"
            
            
            id="friends">
            <i class='fas fa-link fa-fw'></i>&nbsp;友链
          </a>
        </li>
      
        <li>
          <a class="nav home" href="/about/"
            
              rel="nofollow"
            
            
            id="about">
            <i class='fas fa-info-circle fa-fw'></i>&nbsp;关于
          </a>
        </li>
      
    
  </ul>
</div>

      
    </cover>
    <header class="l_header pure">
  <div id="loading-bar-wrapper">
    <div id="loading-bar" class="pure"></div>
  </div>

	<div class='wrapper'>
		<div class="nav-main container container--flex">
      <a class="logo flat-box" href='/' >
        
          梁健的博客
        
      </a>
			<div class='menu navgation'>
				<ul class='h-list'>
          
  					
  						<li>
								<a class="nav flat-box" href="/categories/"
                  
                    rel="nofollow"
                  
                  
                  id="categories">
									<i class='fas fa-folder-open fa-fw'></i>&nbsp;分类
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="/tags/"
                  
                    rel="nofollow"
                  
                  
                  id="tags">
									<i class='fas fa-hashtag fa-fw'></i>&nbsp;标签
								</a>
							</li>
      			
  						<li>
								<a class="nav flat-box" href="/archives/"
                  
                    rel="nofollow"
                  
                  
                  id="archives">
									<i class='fas fa-archive fa-fw'></i>&nbsp;归档
								</a>
							</li>
      			
      		
				</ul>
			</div>

			
				<div class="m_search">
					<form name="searchform" class="form u-search-form">
						<input type="text" class="input u-search-input" placeholder="搜索" />
						<i class="icon fas fa-search fa-fw"></i>
					</form>
				</div>
			
			<ul class='switcher h-list'>
				
					<li class='s-search'><a class="fas fa-search fa-fw" href='javascript:void(0)'></a></li>
				
				<li class='s-menu'><a class="fas fa-bars fa-fw" href='javascript:void(0)'></a></li>
			</ul>
		</div>

		<div class='nav-sub container container--flex'>
			<a class="logo flat-box"></a>
			<ul class='switcher h-list'>
				<li class='s-comment'><a class="flat-btn fas fa-comments fa-fw" href='javascript:void(0)'></a></li>
        
          <li class='s-toc'><a class="flat-btn fas fa-list fa-fw" href='javascript:void(0)'></a></li>
        
			</ul>
		</div>
	</div>
</header>
	<aside class="menu-phone">
    <header>
		<nav class="menu navgation">
      <ul>
        
          
            <li>
							<a class="nav flat-box" href="/"
                
                
                id="home">
								<i class='fas fa-clock fa-fw'></i>&nbsp;近期文章
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/archives/"
                
                  rel="nofollow"
                
                
                id="archives">
								<i class='fas fa-archive fa-fw'></i>&nbsp;文章归档
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/projects/"
                
                
                id="projects">
								<i class='fas fa-code-branch fa-fw'></i>&nbsp;开源项目
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/friends/"
                
                  rel="nofollow"
                
                
                id="friends">
								<i class='fas fa-link fa-fw'></i>&nbsp;我的友链
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="https://xaoxuu.com/wiki/material-x/"
                
                  rel="nofollow"
                
                
                id="https:xaoxuu.comwikimaterial-x">
								<i class='fas fa-book fa-fw'></i>&nbsp;主题文档
							</a>
            </li>
          
            <li>
							<a class="nav flat-box" href="/about/"
                
                  rel="nofollow"
                
                
                id="about">
								<i class='fas fa-info-circle fa-fw'></i>&nbsp;关于小站
							</a>
            </li>
          
       
      </ul>
		</nav>
    </header>
	</aside>
<script>setLoadingBarProgress(40);</script>

  </div>


  <div class="l_body">
    <div class='body-wrapper'>
      <div class='l_main'>
  

  <article id="post" class="post white-box article-type-post" itemscope itemprop="blogPost">
    


  <section class='meta'>
    
    
    <div class="meta" id="header-meta">
      
        
  
    <h1 class="title">
      <a href="/2020/01/07/Android%20%E9%9B%86%E6%88%90%E5%BE%AE%E4%BF%A1%E7%99%BB%E5%BD%95/">
        Android 集成微信登录
      </a>
    </h1>
  


      
      <div class='new-meta-box'>
        
          
        
          
            
  <div class='new-meta-item author'>
    
      <a href="https://abiubiubiua.gitee.io" rel="nofollow">
        
          <i class="fas fa-user" aria-hidden="true"></i>
        
        <p>Jian Liang</p>
      </a>
    
  </div>


          
        
          
            <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt" aria-hidden="true"></i>
    <p>2020-01-07</p>
  </a>
</div>

          
        
          
            

          
        
          
            
  
    <div class="new-meta-item browse busuanzi">
      <a class='notlink'>
        <i class="fas fa-eye" aria-hidden="true"></i>
        <p>
          <span id="busuanzi_value_page_pv">
            <i class="fas fa-spinner fa-spin fa-fw" aria-hidden="true"></i>
          </span>
        </p>
      </a>
    </div>
  


          
        
          
            
  
    <div class="new-meta-item wordcount">
      <a class='notlink'>
        <i class="fas fa-keyboard" aria-hidden="true"></i>
        <p>字数统计:</p>
        <p>2.1k字</p>
      </a>
    </div>
    <div class="new-meta-item readtime">
      <a class='notlink'>
        <i class="fas fa-hourglass-half" aria-hidden="true"></i>
        <p>阅读时长≈</p>
        <p>8分</p>
      </a>
    </div>
  

          
        
          
            

          
        
      </div>
      
        <hr>
      
    </div>
  </section>


    <section class="article typo">
      <div class="article-entry" itemprop="articleBody">
        <p>今天项目中集成微信登录，以为非常顺利的事情，却还是多多少少出现了一些问题。所以记录一下集成过程中出现的问题。</p>
<h1 id="开发环境："><a href="#开发环境：" class="headerlink" title="开发环境："></a>开发环境：</h1><ul>
<li><input checked="" disabled="" type="checkbox"> 系统环境：<code>windows10</code></li>
<li><input checked="" disabled="" type="checkbox"> AndroidStudio 版本: <code>3.3.2</code></li>
<li><input checked="" disabled="" type="checkbox"> Gradle 版本：<code>3.3.2</code></li>
</ul>
<p>#集成过程（参照微信接入指南（<a href="https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417751808&token=60cf535dd0331502a793d5f32051b033b24b9e9d&lang=zh_CN" target="_blank" rel="noopener">https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&amp;t=resource/res_list&amp;verify=1&amp;id=1417751808&amp;token=60cf535dd0331502a793d5f32051b033b24b9e9d&amp;lang=zh_CN</a>））</p>
<ol>
<li>在项目gradle添加依赖<br>//微信<br>implementation ‘com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+’</li>
</ol>
<p>2.注册申请好的AppId到微信（必须在调用登录功能之前）<br>// APP_ID<br>private static final String APP_ID = “自己的appId”;<br>api = WXAPIFactory.createWXAPI(context, APP_ID, true);</p>
<p>// 将应用的appId注册到微信<br>api.registerApp(APP_ID);</p>
<p>3.发送登录请求（）<br>SendAuth.Req req = new SendAuth.Req();<br>req.scope = “snsapi_userinfo”;<br>req.state = “111”;<br>api.sendReq(req);</p>
<p>参数说明</p>
<p>来源： <a href="https://open.weixin.qq.com/cgi-bin/showdocument?action=doc&id=open1419317851&t=0.2650837650069082" target="_blank" rel="noopener">https://open.weixin.qq.com/cgi-bin/showdocument?action=doc&amp;id=open1419317851&amp;t=0.2650837650069082</a></p>
<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 855px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 73px;">参数</th><th style="width: 49px;">是否必须</th><th style="width: 733px;">说明</th></tr></thead><tbody><tr><td style="width: 73px;">appid</td><td style="width: 49px;">是</td><td style="width: 733px;">应用唯一标识，在微信开放平台提交应用审核通过后获得</td></tr><tr><td style="width: 73px;">scope</td><td style="width: 49px;">是</td><td style="width: 733px;">应用授权作用域，如获取用户个人信息则填写snsapi_userinfo（<span>&nbsp;</span><a href="https://open.weixin.qq.com/cgi-bin/showdocument?action=doc&amp;id=open1419317851&amp;t=0.2650837650069082#0" target="_blank" rel="noopener" style="color:rgb(50, 146, 255);text-decoration:none;">什么是授权域？</a><span>&nbsp;</span>）</td></tr><tr><td style="width: 73px;">state</td><td style="width: 49px;">否</td><td style="width: 733px;">用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止csrf攻击（跨站请求伪造攻击），建议第三方带上该参数，可设置为简单的随机数加session进行校验</td></tr></tbody></table></div></div>

<p>4.在项目包名下创建wxapi包并且创建<a href="file:///D:/asWorkSpace/Fiance/app/src/main/java/com/xsp/finance/wxapi/WXEntryActivity.java">WXEntryActivity</a>,并且在<a href="file:///D:/asWorkSpace/Fiance/app/src/main/AndroidManifest.xml">AndroidManifest</a>中配置,配置必须与下图中一致。<br>![tempsnip.png](Android 集成微信登录_files/tempsnip.png)</p>
<!--微信回调-->
<p><activity
    android:name=".wxapi.WXEntryActivity"
    android:label="WXEntryActivity"
    android:exported="true"
    android:launchMode="singleTask"
    android:taskAffinity="包名"></activity></p>
<p>5.在<a href="file:///D:/asWorkSpace/Fiance/app/src/main/java/com/xsp/finance/wxapi/WXEntryActivity.java">WXEntryActivity</a>中,实现 IWXAPIEventHandler 接口。在oncreate方法中注册回调<br>api.handleIntent(getIntent(), this);<br>如果不注册,则收不到回调（我刚开始没有注册该回调，导致一直收不到回调信息）。</p>
<p>6.在项目gradle中配置签名文件,必须与平台中的签名一致。<br>android {<br>buildTypes {<br>    release {<br>        minifyEnabled false<br>        proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’<br>    }</p>
<pre><code>debug{
    signingConfig signingConfigs.debug // 配置debug包的签名
}</code></pre><p>}</p>
<p>signingConfigs {<br>    debug {<br>        storeFile file(“签名路径/debug.keystore”)<br>        storePassword “android”<br>        keyAlias “androiddebugkey”<br>        keyPassword “android”<br>    }<br>}<br>}<br>到这里就集成成功了，我遇到的问题主要是没有注册回调，导致收不到信息。<br>关于<a href="file:///D:/asWorkSpace/Fiance/app/src/main/java/com/xsp/finance/wxapi/WXEntryActivity.java">WXEntryActivity</a>中,实现 IWXAPIEventHandler 接口后,根据微信提供的文档以及业务需要继续下去就好了：<br>@Override<br>public void onReq(BaseReq baseReq) {</p>
<p>}</p>
<p>@Override<br>public void onResp(BaseResp baseResp) {<br>Log.e(TAG, ((SendAuth.Resp) baseResp).code +<br>“–” + ((SendAuth.Resp) baseResp).url +<br>“–” + baseResp.getType() +<br>“–” + baseResp.errCode +<br>“–” + ((SendAuth.Resp) baseResp).state +<br>“–” + ((SendAuth.Resp) baseResp).lang);<br>}</p>
<p>返回说明<br>用户点击授权后，微信客户端会被拉起，跳转至授权界面，用户在该界面点击允许或取消，SDK通过SendAuth的Resp返回数据给调用方。</p>
<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 858px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 85px;">返回值</th><th style="width: 773px;">说明</th></tr></thead><tbody><tr><td style="width: 85px;">ErrCode</td><td style="width: 773px;">ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权） ERR_USER_CANCEL = -2（用户取消）</td></tr><tr><td style="width: 85px;">code</td><td style="width: 773px;">用户换取access_token的code，仅在ErrCode为0时有效</td></tr><tr><td style="width: 85px;">state</td><td style="width: 773px;">第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K</td></tr><tr><td style="width: 85px;">lang</td><td style="width: 773px;">微信客户端当前语言</td></tr><tr><td style="width: 85px;">country</td><td style="width: 773px;">微信用户当前国家信息</td></tr></tbody></table></div></div>

<p>第二步：通过code获取access_token<br>获取第一步的code后，请求以下链接获取access_token：<br><a href="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&amp;secret=SECRET&amp;code=CODE&amp;grant_type=authorization_code" target="_blank" rel="noopener">https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&amp;secret=SECRET&amp;code=CODE&amp;grant_type=authorization_code</a><br>参数说明</p>
<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 852px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 135px;">参数</th><th style="width: 112px;">是否必须</th><th style="width: 605px;">说明</th></tr></thead><tbody><tr><td style="width: 135px;">appid</td><td style="width: 112px;">是</td><td style="width: 605px;">应用唯一标识，在微信开放平台提交应用审核通过后获得</td></tr><tr><td style="width: 135px;">secret</td><td style="width: 112px;">是</td><td style="width: 605px;">应用密钥AppSecret，在微信开放平台提交应用审核通过后获得</td></tr><tr><td style="width: 135px;">code</td><td style="width: 112px;">是</td><td style="width: 605px;">填写第一步获取的code参数</td></tr><tr><td style="width: 135px;">grant_type</td><td style="width: 112px;">是</td><td style="width: 605px;">填authorization_code</td></tr></tbody></table></div></div>


<p>返回说明<br>正确的返回：<br>{<br>“access_token”:”ACCESS_TOKEN”,<br>“expires_in”:7200,<br>“refresh_token”:”REFRESH_TOKEN”,<br>“openid”:”OPENID”,<br>“scope”:”SCOPE”,<br>“unionid”:”o6_bmasdasdsad6_2sgVt7hMZOPfL”<br>}</p>
<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 855px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 169px;">参数</th><th style="width: 685px;">说明</th></tr></thead><tbody><tr><td style="width: 169px;">access_token</td><td style="width: 685px;">接口调用凭证</td></tr><tr><td style="width: 169px;">expires_in</td><td style="width: 685px;">access_token接口调用凭证超时时间，单位（秒）</td></tr><tr><td style="width: 169px;">refresh_token</td><td style="width: 685px;">用户刷新access_token</td></tr><tr><td style="width: 169px;">openid</td><td style="width: 685px;">授权用户唯一标识</td></tr><tr><td style="width: 169px;">scope</td><td style="width: 685px;">用户授权的作用域，使用逗号（,）分隔</td></tr><tr><td style="width: 169px;">unionid</td><td style="width: 685px;">当且仅当该移动应用已获得该用户的userinfo授权时，才会出现该字段</td></tr></tbody></table></div></div>

<p>错误返回样例：<br>{“errcode”:40029,”errmsg”:”invalid code”}<br>刷新access_token有效期<br>access_token是调用授权关系接口的调用凭证，由于access_token有效期（目前为2个小时）较短，当access_token超时后，可以使用refresh_token进行刷新，access_token刷新结果有两种：</p>
<ol>
<li>若access_token已超时，那么进行refresh_token会获取一个新的access_token，新的超时时间；</li>
<li>若access_token未超时，那么进行refresh_token不会改变access_token，但超时时间会刷新，相当于续期access_token。<br>refresh_token拥有较长的有效期（30天），当refresh_token失效的后，需要用户重新授权。<br>请求方法<br>获取第一步的code后，请求以下链接进行refresh_token：<br><a href="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&amp;grant_type=refresh_token&amp;refresh_token=REFRESH_TOKEN" target="_blank" rel="noopener">https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&amp;grant_type=refresh_token&amp;refresh_token=REFRESH_TOKEN</a><br>参数说明<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 865px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 183px;">参数</th><th style="width: 124px;">是否必须</th><th style="width: 557px;">说明</th></tr></thead><tbody><tr><td style="width: 183px;">appid</td><td style="width: 124px;">是</td><td style="width: 557px;">应用唯一标识</td></tr><tr><td style="width: 183px;">grant_type</td><td style="width: 124px;">是</td><td style="width: 557px;">填refresh_token</td></tr><tr><td style="width: 183px;">refresh_token</td><td style="width: 124px;">是</td><td style="width: 557px;">填写通过access_token获取到的refresh_token参数</td></tr></tbody></table></div></div>

</li>
</ol>
<p>返回说明<br>正确的返回：<br>{<br>“access_token”:”ACCESS_TOKEN”,<br>“expires_in”:7200,<br>“refresh_token”:”REFRESH_TOKEN”,<br>“openid”:”OPENID”,<br>“scope”:”SCOPE”<br>}</p>
<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 863px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 217px;">参数</th><th style="width: 645px;">说明</th></tr></thead><tbody><tr><td style="width: 217px;">access_token</td><td style="width: 645px;">接口调用凭证</td></tr><tr><td style="width: 217px;">expires_in</td><td style="width: 645px;">access_token接口调用凭证超时时间，单位（秒）</td></tr><tr><td style="width: 217px;">refresh_token</td><td style="width: 645px;">用户刷新access_token</td></tr><tr><td style="width: 217px;">openid</td><td style="width: 645px;">授权用户唯一标识</td></tr><tr><td style="width: 217px;">scope</td><td style="width: 645px;">用户授权的作用域，使用逗号（,）分隔</td></tr></tbody></table></div></div>

<p>错误返回样例：<br>{“errcode”:40030,”errmsg”:”invalid refresh_token”}<br>注意：</p>
<p>1、Appsecret 是应用接口使用密钥，泄漏后将可能导致应用数据泄漏、应用的用户数据泄漏等高风险后果；存储在客户端，极有可能被恶意窃取（如反编译获取Appsecret）；<br>2、access_token 为用户授权第三方应用发起接口调用的凭证（相当于用户登录态），存储在客户端，可能出现恶意获取access_token 后导致的用户数据泄漏、用户微信相关接口功能被恶意发起等行为；<br>3、refresh_token 为用户授权第三方应用的长效凭证，仅用于刷新access_token，但泄漏后相当于access_token 泄漏，风险同上。<br>建议将Appsecret、用户数据（如access_token）放在App云端服务器，由云端中转接口调用请求。<br>第三步：通过access_token调用接口<br>获取access_token后，进行接口调用，有以下前提：<br>access_token有效且未超时；<br>微信用户已授权给第三方应用帐号相应接口作用域（scope）。<br>对于接口作用域（scope），能调用的接口有以下：</p>
<div class="wiz-table-container" style="position: relative; padding: 0px;"><div class="wiz-table-body"><table style="width: 845px; font-size: 0.875rem; color: rgb(34, 34, 34); font-family: 'Hiragino Sans GB', 'Microsoft YaHei', 黑体, Helvetica, Arial, Tahoma, sans-serif;"><thead style="background-color:rgb(240, 240, 240);"><tr><th style="width: 199px;">授权作用域（scope）</th><th style="width: 208px;">接口</th><th style="width: 437px;">接口说明</th></tr></thead><tbody><tr><td style="width: 199px;">snsapi_base</td><td style="width: 208px;">/sns/oauth2/access_token</td><td style="width: 437px;">通过code换取access_token、refresh_token和已授权scope</td></tr><tr><td style="width: 199px;">/sns/oauth2/refresh_token</td><td style="width: 208px;">刷新或续期access_token使用</td></tr><tr><td style="width: 199px;">/sns/auth</td><td style="width: 208px;">检查access_token有效性</td></tr><tr><td style="width: 199px;">snsapi_userinfo</td><td style="width: 208px;">/sns/userinfo</td><td style="width: 437px;">获取用户个人信息</td></tr></tbody></table></div></div>
其中snsapi_base属于基础接口，若应用已拥有其它scope权限，则默认拥有snsapi_base的权限。使用snsapi_base可以让移动端网页授权绕过跳转授权登录页请求用户授权的动作，直接跳转第三方网页带上授权临时票据（code），但会使得用户已授权作用域（scope）仅为snsapi_base，从而导致无法获取到需要用户授权才允许获得的数据和基础功能。
接口调用方法可查阅[《微信授权关系接口调用指南》](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317853&lang=zh_CN)
F.A.Q
1. 什么是授权临时票据（code）？
答：第三方通过code进行获取access_token的时候需要用到，code的超时时间为10分钟，一个code只能成功换取一次access_token即失效。code的临时性和一次保障了微信授权登录的安全性。第三方可通过使用https和state参数，进一步加强自身授权登录的安全性。
2. 什么是授权作用域（scope）？
答：授权作用域（scope）代表用户授权给第三方的接口权限，第三方应用需要向微信开放平台申请使用相应scope的权限后，使用文档所述方式让用户进行授权，经过用户授权，获取到相应access_token后方可对接口进行调用。
3.开放平台移动应用微信登录目前是否收费？
答：“微信登录”和第三方网站共享微信庞大的用户价值，同时为微信用户提供更便捷服务和更优质内容，实现双向共赢，目前不收取任何费用。

<p>文章部分内容转载微信开放平台 <a href="https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=60cf535dd0331502a793d5f32051b033b24b9e9d&lang=zh_CN" target="_blank" rel="noopener">https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&amp;t=resource/res_list&amp;verify=1&amp;id=open1419317851&amp;token=60cf535dd0331502a793d5f32051b033b24b9e9d&amp;lang=zh_CN</a></p>

      </div>
      
      
        <br>
        


  <section class='meta' id="footer-meta">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2020-01-07T20:28:32+08:00">
  <a class='notlink'>
    <i class="fas fa-clock" aria-hidden="true"></i>
    <p>更新于 2020年1月7日</p>
  </a>
</div>

        
      
        
          

        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="QQ好友" rel="external nofollow noopener noreferrer"
          
          href="http://connect.qq.com/widget/shareqq/index.html?url=https://abiubiubiua.gitee.io/2020/01/07/Android%20%E9%9B%86%E6%88%90%E5%BE%AE%E4%BF%A1%E7%99%BB%E5%BD%95/&title=Android 集成微信登录 | 梁健的博客&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/assets@19.1.9/logo/128/qq.png">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="QQ空间" rel="external nofollow noopener noreferrer"
          
          href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://abiubiubiua.gitee.io/2020/01/07/Android%20%E9%9B%86%E6%88%90%E5%BE%AE%E4%BF%A1%E7%99%BB%E5%BD%95/&title=Android 集成微信登录 | 梁健的博客&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/assets@19.1.9/logo/128/qzone.png">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="微博" rel="external nofollow noopener noreferrer"
          
          href="http://service.weibo.com/share/share.php?url=https://abiubiubiua.gitee.io/2020/01/07/Android%20%E9%9B%86%E6%88%90%E5%BE%AE%E4%BF%A1%E7%99%BB%E5%BD%95/&title=Android 集成微信登录 | 梁健的博客&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/assets@19.1.9/logo/128/weibo.png">
          
        </a>
      
    
  </div>
</div>



        
      
    </div>
  </section>


      
      
          <div class="prev-next">
              
                  <section class="prev">
                      <span class="art-item-left">
                          <h6><i class="fas fa-chevron-left" aria-hidden="true"></i>&nbsp;上一页</h6>
                          <h4>
                              <a href="/2020/01/09/2019%E5%B7%A5%E4%BD%9C%E6%80%BB%E7%BB%93/" rel="prev" title="2019工作总结">
                                
                                    2019工作总结
                                
                              </a>
                          </h4>
                          
                      </span>
                  </section>
              
              
                  <section class="next">
                      <span class="art-item-right" aria-hidden="true">
                          <h6>下一页&nbsp;<i class="fas fa-chevron-right" aria-hidden="true"></i></h6>
                          <h4>
                              <a href="/2020/01/07/hello-world/" rel="prev" title="Hello World">
                                  
                                      Hello World
                                  
                              </a>
                          </h4>
                          
                      </span>
                  </section>
              
          </div>
      
    </section>
  </article>



  <!-- 显示推荐文章和评论 -->



  <article class="post white-box comments">
    <section class="article typo">
      <h4><i class="fas fa-comments fa-fw" aria-hidden="true"></i>&nbsp;评论</h4>
      
      
      
      
        <section id="comments">
          <div id="valine_container" class="valine_thread">
            <i class="fas fa-spinner fa-spin fa-fw"></i>
          </div>
        </section>
      
    </section>
  </article>






<!-- 根据页面mathjax变量决定是否加载MathJax数学公式js -->



  <script>
    window.subData = {
      title: 'Android 集成微信登录',
      tools: true
    }
  </script>


</div>
<aside class='l_side'>
  
    
    
      
      
        
          
          
            
              <section class='widget author'>
  <div class='content pure'>
    
      <div class='avatar'>
        <img class='avatar' src='/icon/head.jpg'/>
      </div>
    
    
      <div class='text'>
        
        
        
          <p><span id="jinrishici-sentence">梁健的博客</span></p>
          <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
        
      </div>
    
    
      <div class="social-wrapper">
        
          
            <a href="/atom.xml"
              class="social fas fa-rss flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
          
            <a href="mailto:13521074393@sina.cn"
              class="social fas fa-envelope flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
          
            <a href="https://gitee.com/Abiubiubiua"
              class="social fab fa-gitee flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
          
            <a href="https://music.163.com/#/user/home?id=100406942"
              class="social fas fa-headphones-alt flat-btn"
              target="_blank"
              rel="external nofollow noopener noreferrer">
            </a>
          
        
      </div>
    
  </div>
</section>

            
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
      
        
          
          
        
          
          
            
              <section class='widget plain'>
  
<header class='pure'>
  <div><i class="fa fa-comments fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;这是我的微信</div>
  
</header>

  <div class='content pure'>
    <p><img src="https://abiubiubiua.gitee.io/icon/wechat.jpg" alt=""></p>

  </div>
</section>

            
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
      
        
          
          
        
          
          
        
          
          
            
              
  <section class='widget toc-wrapper'>
    
<header class='pure'>
  <div><i class="fas fa-list fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;本文目录</div>
  
    <!-- <div class='wrapper'><a class="s-toc rightBtn" rel="external nofollow noopener noreferrer" href="javascript:void(0)"><i class="fas fa-thumbtack fa-fw"></i></a></div> -->
  
</header>

    <div class='content pure'>
      <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#开发环境："><span class="toc-text">开发环境：</span></a></li></ol>
    </div>
  </section>


            
          
        
          
          
        
          
          
        
          
          
        
          
          
        
      
        
          
          
        
          
          
        
          
          
        
          
          
            
              <section class='widget grid'>
  
<header class='pure'>
  <div><i class="fas fa-map-signs fa-fw" aria-hidden="true"></i>&nbsp;&nbsp;站内导航</div>
  
</header>

  <div class='content pure'>
    <ul class="grid navgation">
      
        <li><a class="flat-box" title="/" href="/"
          
          
          id="home">
          
            <i class="fas fa-clock fa-fw" aria-hidden="true"></i>
          
          近期文章
        </a></li>
      
        <li><a class="flat-box" title="/archives/" href="/archives/"
          
            rel="nofollow"
          
          
          id="archives">
          
            <i class="fas fa-archive fa-fw" aria-hidden="true"></i>
          
          文章归档
        </a></li>
      
        <li><a class="flat-box" title="/projects/" href="/projects/"
          
          
          id="projects">
          
            <i class="fas fa-code-branch fa-fw" aria-hidden="true"></i>
          
          开源项目
        </a></li>
      
        <li><a class="flat-box" title="/friends/" href="/friends/"
          
            rel="nofollow"
          
          
          id="friends">
          
            <i class="fas fa-link fa-fw" aria-hidden="true"></i>
          
          我的友链
        </a></li>
      
        <li><a class="flat-box" title="https://xaoxuu.com/wiki/material-x/" href="https://xaoxuu.com/wiki/material-x/"
          
            rel="nofollow"
          
          
          id="https:xaoxuu.comwikimaterial-x">
          
            <i class="fas fa-book fa-fw" aria-hidden="true"></i>
          
          主题文档
        </a></li>
      
        <li><a class="flat-box" title="/about/" href="/about/"
          
            rel="nofollow"
          
          
          id="about">
          
            <i class="fas fa-info-circle fa-fw" aria-hidden="true"></i>
          
          关于小站
        </a></li>
      
    </ul>
  </div>
</section>

            
          
        
          
          
        
          
          
        
          
          
        
      
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
            
              

            
          
        
          
          
        
          
          
        
      
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
            
              

            
          
        
          
          
        
      
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
      
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
          
          
        
      
    

  
</aside>

<footer id="footer" class="clearfix">
  
  
    <div class="social-wrapper">
      
        
          <a href="/atom.xml"
            class="social fas fa-rss flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
        
          <a href="mailto:13521074393@sina.cn"
            class="social fas fa-envelope flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
        
          <a href="https://gitee.com/Abiubiubiua"
            class="social fab fa-gitee flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
        
          <a href="https://music.163.com/#/user/home?id=100406942"
            class="social fas fa-headphones-alt flat-btn"
            target="_blank"
            rel="external nofollow noopener noreferrer">
          </a>
        
      
    </div>
  
  <br>
  <div><p>博客内容遵循 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p>
</div>
  <div>
    本站使用
    <a href="https://xaoxuu.com/wiki/material-x/" target="_blank" class="codename">Material X</a>
    作为主题
    
      ，
      总访问量为
      <span id="busuanzi_value_site_pv"><i class="fas fa-spinner fa-spin fa-fw" aria-hidden="true"></i></span>
      次
    
    。
  </div>
</footer>
<script>setLoadingBarProgress(80);</script>


      <script>setLoadingBarProgress(60);</script>
    </div>
    <a class="s-top fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>

  <script>
    var GOOGLE_CUSTOM_SEARCH_API_KEY = "";
    var GOOGLE_CUSTOM_SEARCH_ENGINE_ID = "";
    var ALGOLIA_API_KEY = "";
    var ALGOLIA_APP_ID = "";
    var ALGOLIA_INDEX_NAME = "";
    var AZURE_SERVICE_NAME = "";
    var AZURE_INDEX_NAME = "";
    var AZURE_QUERY_KEY = "";
    var BAIDU_API_ID = "";
    var SEARCH_SERVICE = "hexo" || "hexo";
    var ROOT = "/"||"/";
    if(!ROOT.endsWith('/'))ROOT += '/';
  </script>

<script src="//instant.page/1.2.2" type="module" integrity="sha384-2xV8M5griQmzyiY3CDqh1dn4z3llDVqZDqzjzcY+jCBCk/a5fXJmuZ/40JJAPeoU"></script>


  <script async src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.5/dist/scrollreveal.min.js"></script>
  <script type="text/javascript">
    $(function() {
      const $reveal = $('.reveal');
      if ($reveal.length === 0) return;
      const sr = ScrollReveal({ distance: 0 });
      sr.reveal('.reveal');
    });
  </script>


  <script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>
  <script type="text/javascript">
    $(function() {
      Waves.attach('.flat-btn', ['waves-button']);
      Waves.attach('.float-btn', ['waves-button', 'waves-float']);
      Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
      Waves.attach('.flat-box', ['waves-block']);
      Waves.attach('.float-box', ['waves-block', 'waves-float']);
      Waves.attach('.waves-image');
      Waves.init();
    });
  </script>


  <script async src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js"></script>




  
  
  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
    <script type="text/javascript">
      $(function(){
        if ('') {
          $('').backstretch(
          ["https://img.vim-cn.com/29/91197b04c13f512f734a76d4ac422d89dbe229.jpg"],
          {
            duration: "6000",
            fade: "2500"
          });
        } else {
          $.backstretch(
          ["https://img.vim-cn.com/29/91197b04c13f512f734a76d4ac422d89dbe229.jpg"],
          {
            duration: "6000",
            fade: "2500"
          });
        }
      });
    </script>
  









  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
    
      
<script src="/js/volantis.js"></script>

    
  
  <script>
  var GUEST_INFO = ['nick','mail','link'];
  var guest_info = 'nick,mail'.split(',').filter(function(item){
    return GUEST_INFO.indexOf(item) > -1
  });
  var notify = 'true' == true;
  var verify = 'true' == true;
  var valine = new Valine();
  valine.init({
    el: '#valine_container',
    notify: notify,
    verify: verify,
    guest_info: guest_info,
    
    appId: "qaATcIgHcSeXM3vz9PtpqMGY-gzGzoHsz",
    appKey: "Sf5vE2uV2p0IkhVUDA5oqV0Q",
    placeholder: "快来评论吧~",
    pageSize:'10',
    avatar:'mp',
    lang:'zh-cn',
    highlight:'true'
  })
  </script>



  
<script src="/js/app.js"></script>



  
<script src="/js/search.js"></script>





<!-- 复制 -->
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  let COPY_SUCCESS = "复制成功";
  let COPY_FAILURE = "复制失败";
  /*页面载入完成后，创建复制按钮*/
  !function (e, t, a) {
    /* code */
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '  <i class="fa fa-copy"></i><span>复制</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });

      clipboard.on('success', function(e) {
        //您可以加入成功提示
        console.info('Action:', e.action);
        console.info('Text:', e.text);
        console.info('Trigger:', e.trigger);
        success_prompt(COPY_SUCCESS);
        e.clearSelection();
      });
      clipboard.on('error', function(e) {
        //您可以加入失败提示
        console.error('Action:', e.action);
        console.error('Trigger:', e.trigger);
        fail_prompt(COPY_FAILURE);
      });
    }
    initCopyCode();

  }(window, document);

  /**
   * 弹出式提示框，默认1.5秒自动消失
   * @param message 提示信息
   * @param style 提示样式，有alert-success、alert-danger、alert-warning、alert-info
   * @param time 消失时间
   */
  var prompt = function (message, style, time)
  {
      style = (style === undefined) ? 'alert-success' : style;
      time = (time === undefined) ? 1500 : time*1000;
      $('<div>')
          .appendTo('body')
          .addClass('alert ' + style)
          .html(message)
          .show()
          .delay(time)
          .fadeOut();
  };

  // 成功提示
  var success_prompt = function(message, time)
  {
      prompt(message, 'alert-success', time);
  };

  // 失败提示
  var fail_prompt = function(message, time)
  {
      prompt(message, 'alert-danger', time);
  };

  // 提醒
  var warning_prompt = function(message, time)
  {
      prompt(message, 'alert-warning', time);
  };

  // 信息提示
  var info_prompt = function(message, time)
  {
      prompt(message, 'alert-info', time);
  };

</script>


<!-- fancybox -->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
<script>
  let LAZY_LOAD_IMAGE = "";
  $(".article-entry").find("fancybox").find("img").each(function () {
      var element = document.createElement("a");
      $(element).attr("data-fancybox", "gallery");
      $(element).attr("href", $(this).attr("src"));
      /* 图片采用懒加载处理时,
       * 一般图片标签内会有个属性名来存放图片的真实地址，比如 data-original,
       * 那么此处将原本的属性名src替换为对应属性名data-original,
       * 修改如下
       */
       if (LAZY_LOAD_IMAGE) {
         $(element).attr("href", $(this).attr("data-original"));
       }
      $(this).wrap(element);
  });
</script>





  <script>setLoadingBarProgress(100);</script>
</body>
</html>
